package com.herohead.redis;

import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONObject;

import redis.clients.jedis.Jedis;

import com.herohead.Misc;



public class SendLog {

	static String redisHost;
	static int maxLogSize = 10000;
	static Map<String, String> messageList = new HashMap<String, String>();


	@SuppressWarnings("rawtypes")
	public static Map getMap() {
		return messageList;
	}

	StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();

	public void addToMessage(String key, String val) {
		messageList.put(key, val);
	}

	@SuppressWarnings({ "unchecked"})
	public String createJson() {
		JSONObject jsobj = new JSONObject();

		jsobj.putAll(messageList);
		return jsobj.toJSONString();
	}

	public  String getKeyFromMessage(String key) {
		return messageList.get(key);
	}

	public int getMaxLogSize() {
		return maxLogSize;
	}

	public String getRedisHost() {
		return redisHost;
	}

	public int sendLog (String redisKey, String strJson) {


		return 0;
	}

	public void setLog(String logKey,String type,String sev,String program,String logName, String logTitle, String logDetail) {

		if (messageList.isEmpty()) {messageList.clear();}

		addToMessage("timestamp", Misc.getTimestamp());
		addToMessage("ProgramName", stackTraceElements[2].toString());
		addToMessage("IPaddress", Misc.getLocalHostIPaddress());

		addToMessage("type", type);
		addToMessage("sev", sev);
		addToMessage("program", program);
		addToMessage("logName", logName);
		addToMessage("logTitle", logTitle);
		addToMessage("logDetail", logDetail);

	}


	public void setLogandWrite(String logKey,String type,String sev,String program,String logName, String logTitle, String logDetail) {

		setLog(logKey,type,sev,program,logName, logTitle, logDetail);
		writeLog(logKey);
	}

	public void setMaxLogSize(int logSize) {
		maxLogSize = logSize;
	}

	public void setRedisHost(String StrredisHost) {
		redisHost = StrredisHost;
	}

	public void trimLog(String logKey) {
		Jedis jd = new Jedis(redisHost);
		jd.ltrim(logKey, 0, maxLogSize-1);
		jd.close();
	}

	public void writeLog(String logKey){

		if (messageList.isEmpty()) addToMessage("Error", "No log data found");

		Jedis jd = new Jedis(redisHost);
		jd.lpush(logKey, createJson());
		trimLog(logKey);
		jd.close();
	}
}